LOCAL_IP_ADDR="192.168.1.10"
BASE_DIR=/sys/kernel/config/nvmet
PORT_DIR="${BASE_DIR}/ports"
SUBSYS_DIR="${BASE_DIR}/subsystems"

modprobe nvme-tcp
modprobe nvmet-tcp

if [ ! -d "${BASE_DIR}" ]
then
    echo "Dir not exist: ${BASE_DIR}"
    exit 1
fi

function create_port()
{
    local port_name="${1}"

    cd "${PORT_DIR}"
    mkdir "${port_name}"
    cd "${port_name}"
    echo ${LOCAL_IP_ADDR} > "addr_traddr"
    echo tcp > "addr_trtype"
    echo 4420 > "addr_trsvcid"
    echo ipv4 > "addr_adrfam"
}

function create_subsys()
{
    local subsys_name="${1}"
    local port_name="${2}"
    local target="${PORT_DIR}/${port_name}/subsystems/${subsys_name}"

    cd "${SUBSYS_DIR}"
    mkdir "${subsys_name}"
    cd "${subsys_name}"
    echo 1 > attr_allow_any_host
    ln -s "${SUBSYS_DIR}/${subsys_name}" "${target}"
}

function create_device()
{
    local device_idx="${1}"
    local subsys_name="${2}"

    cd "${SUBSYS_DIR}/${subsys_name}"
    mkdir "namespaces/${device_idx}"
    echo /dev/nvme0n1 > "namespaces/${device_idx}/device_path"
    echo 1 > "namespaces/${device_idx}/enable"
}

# create_port "1"
# create_subsys "nvme-tcp" "1"

create_device "2" "nvme-tcp"

# ls "${PORT_DIR}"
# ls "${SUBSYS_DIR}"

# nvme discover -t tcp -a ${LOCAL_IP_ADDR} -s 4420
# nvme connect -t tcp -n nvme-tcp -a ${LOCAL_IP_ADDR} -s 4420
# nvme list
